/**
 * Copyright(c) by JNet Smartware Group.
 * All rights reserved. Not distribution or redistribution without
 * any permission of JNet Smartware Group.
 * 
 * @author thuc
 * 2010/04/12
 */
package vn.smartware.co.framework.logging;

import org.apache.log4j.jdbcplus.JDBCLogger;
import org.apache.log4j.jdbcplus.JDBCSqlHandler;
import org.apache.log4j.spi.LocationInfo;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ThrowableInformation;

import vn.smartware.co.framework.bean.LoginDTO;

/**
 * Custom JDBC SQLHandler to handle statement creation for log statements
 * 
 * @author Thuc
 */
public class SqlHandler implements JDBCSqlHandler {

    private final int MAX_LENGTH_MESSAGE = 3000;

    /**
     * return database SQL statement to log logging event
     * 
     * @param event
     *            the event
     * @return SQL insert statement
     * @throws Exception
     *             if any error occurs
     * @see org.apache.log4j.jdbcplus.JDBCSqlHandler#getStatement(LoggingEvent)
     */
    public String getStatement(LoggingEvent event) throws Exception {
       
        LocationInfo loginfo = event.getLocationInformation();
        ThrowableInformation throwableinfo = event.getThrowableInformation();
        StringBuffer throwableStringBuffer = new StringBuffer();
        String loginfoString = "'', '', '', ''";
        String statement = "";
        LoginDTO user = LoginDTO.getInstance();

        if (loginfo != null) {
            loginfoString = "'" + loginfo.getFileName() + "', '"
					+ loginfo.getMethodName() + "', '"
					+ loginfo.getLineNumber() + "'";
        }
        if (throwableinfo != null) {
			String[] lines = throwableinfo.getThrowableStrRep();
			for (int index = 0; index < lines.length; index++) {
				throwableStringBuffer.append(lines[index] + "\r\n");
			}
		}

        statement = "INSERT INTO ACTIONLOG (prio, thread, class, method, line_number, msg, insert_date, insert_user) ";
        statement += " VALUES ( ";
        statement += "'" + event.getLevel().toString() + "', " 
        		  + "'" + event.getThreadName() + "', " 
                  + loginfoString
                  + ", '" + this.replaceProblematicChars(throwableStringBuffer == null ? "null" : throwableStringBuffer.toString()) + "', " 
        		  + "SYSDATE(), " 
        		  + "'" + user.getLoginName() + "' )";

        return statement;
    }

    /**
     * replaceProblematicChars
     * @param aString
     * @return String
     */
    protected String replaceProblematicChars(String aString) {
        String result = new String(aString);
        // use replace function
        result = new JDBCLogger().replace(result, "'", "''");
        if (result.length() > MAX_LENGTH_MESSAGE) {
            result = result.substring(0, MAX_LENGTH_MESSAGE);
        }

        return result;
    }

}